package com.wave.spring.boot.plugs;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.*;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

/**
 * 监听器是**监听应用启动过程中的不同事件后做出相应动作**。
 * 监听器的接口类是ApplicationListener。
 * 应用启动过程中会通过SpringApplicationRunListener发布事件，
 * 我们只要实现ApplicationListener类，
 * 覆写onApplicationEvent方法来监听这些事件，
 * 就可以在容器启动的各个阶段做一些自定义的事情。
 * 我们已经介绍过，整个容器启动过程中可能发布5种事件，
 * 我们就定制一个CanonCustomApplicationListener全量监听这5种事件，
 * 监听到相应通过日志系统(这里是logback)后打出日志。
 * Created by weibo.xwb on 2017/8/10.
 */
public class CanonCustomApplicationListener implements ApplicationListener {
    private static final Logger logger = LoggerFactory.getLogger(CanonCustomApplicationListener.class);

    @Override
    public void onApplicationEvent(ApplicationEvent event) {

        logger.warn(event.toString());

        // 监听ApplicationStartedEvent
        if (event instanceof ApplicationStartedEvent) {
            logger.warn("Awesome! application started!");
        }
        // 监听ApplicationEnvironmentPreparedEvent
        else if (event instanceof ApplicationEnvironmentPreparedEvent) {
            logger.warn("Awesome! application env prepared!");
        }
        // 监听ApplicationPreparedEvent
        else if (event instanceof ApplicationPreparedEvent) {
            logger.warn("Awesome! application prepared!");
        }

        // 监听ApplicationReadyEvent
        else if (event instanceof ApplicationReadyEvent) {
            logger.warn("Awesome! application was ready!");
        }

        // 监听ApplicationFailedEvent
        else if (event instanceof ApplicationFailedEvent) {
            logger.warn("Help me! application failed!");
        }
    }
}

